<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <j-dialog
        title="查询"
        is-mask
        style="width: 40%"
        :visible.sync="crud.props.searchToggle"
      >
        <el-form size="small" label-width="70px">
          <el-row :gutter="10">
            <el-col span="12">
              <el-form-item label="审核日期">
                <div class="flex flex-row">
                  <el-date-picker
                    v-model="query.startDate"
                    align="right"
                    unlink-panels
                    style="width: 50%"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="开始日期"
                  />
                  <el-date-picker
                    v-model="query.endDate"
                    align="right"
                    unlink-panels
                    style="width: 50%"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="结束日期"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="客户">
                <table-select
                  :tableColumns="[
                    { prop: 'code', label: '客户编码', width: '100' },
                    { prop: 'name', label: '客户名称', width: '150' },
                    { prop: 'address', label: '地址' },
                    { prop: 'sCustomerName', label: '二批' },
                  ]"
                  labelKey="name"
                  valueKey="id"
                  width="700"
                  :value.sync="query.customerIds"
                  placeholder="请选择客户"
                  url="api/dropDown/basCustomerList"
                ></table-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="所属二批">
                <table-select
                  :tableColumns="[{prop:'code',label:'二批编码',width:'100'},{prop:'name',label:'二批名称',width: '280'}]"
                  :value.sync="query.sCustomerIds"
                  placeholder="请选择所属二批"
                  url="/api/dropDown/basCustomerList"
                  :params="{type:3}"
                ></table-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="品牌部门">
                <treeselect
                  v-model="query.goodsBrandDeptIds"
                  :options="deptList"
                  placeholder="请选择部门"
                  style="width: 100%"
                  :normalizer="normalizer"
                  multiple
                  @input="
                    (val) => getNoStr(val, 'deptList', 'goodsBrandDeptIds')
                  "
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="销售部门">
                <treeselect
                  v-model="query.deptIds"
                  :options="deptList"
                  placeholder="请选择部门"
                  style="width: 100%"
                  :normalizer="normalizer"
                  multiple
                  @input="(val) => getNoStr(val, 'deptList', 'deptIds')"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
              <el-form-item label="销售区域">
                <treeselect
                  v-model="customerAreaIds"
                  :options="customerAreaList"
                  placeholder="客户区域"
                  style="width: 100%"
                  :normalizer="normalizer"
                  multiple
                  @input="
                    (val) =>
                      getNoStr(val, 'customerAreaList', 'customerAreaIds')
                  "
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
              <el-form-item label="客户分类">
                <treeselect
                  v-model="customerTypeIds"
                  :options="customerTypeList"
                  placeholder="客户分类"
                  style="width: 100%"
                  :normalizer="normalizer"
                  multiple
                  @input="val=>getNoStr(val,'customerTypeList','customerTypeIds')"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
              <el-form-item label="收款人">
                <table-select
                  :tableColumns="[
                    { prop: 'name', label: '收款人名称', width: '280' },
                  ]"
                  :value.sync="query.payeeUserIds"
                  placeholder="请选择业务员"
                  url="/api/dropDown/sysUserList"
                ></table-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <el-form-item label="客户业务员" label-width="90px">
                <table-select
                  :tableColumns="[
                    { prop: 'name', label: '业务员名称', width: '280' },
                  ]"
                  :value.sync="query.userIds"
                  placeholder="请选择业务员"
                  url="/api/dropDown/sysUserList"
                ></table-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <el-form-item label="只显示超账期" label-width="100px">
                <el-select
                  v-model="query.isOnlyShowOverDate"
                  class="edit-input"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in dict.common_yes_or_no"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
              <el-form-item label="显示全部客户" label-width="100px">
                <el-select
                  v-model="query.isShowAllCustomer"
                  class="edit-input"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="(item, index) in dict.common_yes_or_no"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-form-item label="小计列">
              <el-checkbox-group
                v-model="groupColumn"
                @change="getChange"
                class="flex flex-row flex-wrap"
              >
                <el-checkbox
                  v-for="item in groupColumnList"
                  :label="item.value"
                  :key="item.value"
                  :value="item.value"
                  >{{ item.label }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
          </el-row>
          <el-row>
            <el-col
              :span="24"
              class="flex flex-reverse"
              style="margin-top: 20px"
            >
              <el-button
                class="filter-item"
                size="mini"
                type="primary"
                @click="toQuery"
                >搜索</el-button
              >
              <el-button
                class="filter-item"
                plain
                size="mini"
                type="primary"
                @click="resetQuery"
                >重置
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </j-dialog>
      <j-dialog
        title="设置区间"
        is-mask
        style="width: 40%"
        :visible.sync="showInterval"
      >
        <interval :intervalList="intervalList" @upInterval="upInterval"/>
      </j-dialog>
      <!--表单组件-->
      <crudOperation :permission="permission" >
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="primary"
          @click="showInterval = true"
          v-permission="permission.add"
        >
          设置区间
        </el-button>
      </crudOperation>

      <el-dialog title="表格配置" :visible.sync="tableConfigShow" width="60%">
        <j-table-column-config :columns.sync="header" @tabSave="saveHead" />
      </el-dialog>
      <!--表格渲染-->
      <vue-context-menu
        :contextMenuData="contextMenuData"
        @tableConfig="tableConfig"
      ></vue-context-menu>
      <el-table
        ref="table"
        height="700"
        show-summary
        :summary-method="sumRow" @row-click="crud.selectRow"
        @row-dblclick="toDetail"
        @header-dragend="changeColWidth"
        stripe
        @contextmenu.native="showMenu"
        border
        :data="crud.data"
        size="small"
        style="width: 100%"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="55" label="序号" />
        <el-table-column
          v-if="visible(item)"
          v-for="(item, index) in head"
          :key="item.prop"
          :prop="item.prop"
          :label="columnLabel(item)"
          :width="item.width + 'px'"
          @header-dragend="changeColWidth"
          >
          <el-table-column v-if="item.prop === 'overDateAmountDetail'" :key="item.remark" label="超账期金额" width="120px" v-for="(val,index1) in intervalList" :label="val.remark">
            <template slot-scope="{row}" >
              {{ row[`overDateAmount${`${index1+1}`}`] }}
            </template>
          </el-table-column>

<!--          <template v-else slot-scope="{ row, $index }"-->
<!--            ><span v-if="item.type == 1">{{ row[`${item.prop}`] }}</span-->
<!--            ><span v-else-if="item.type == 2">{{-->
<!--              parseTime(row[`${item.prop}`])-->
<!--            }}</span-->
<!--            ><span v-else-if="item.type == 3">{{-->
<!--              getDict(`this.dict.label.${item.dictionary}[${row[item.prop]}]`)-->
<!--            }}</span-->
<!--            >-->
<!--          </template>-->
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudReportCustomerReceive from "@/api/erp/reportCustomerReceive";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import JDialog from "../../../components/jDialog/jDialog";
import { getCustomerTypeTree } from "@/api/erp/basCustomerType";
import Treeselect from "@riophae/vue-treeselect";
import { tablemixins } from "../../../mixins/tablemixins";
import { manyTableMixin } from "../../../mixins/manyTableMixin";
import jTableColumnConfig from "@/components/jTableColumnConfig/jTableColumnConfig";
import { getCustomerAreaTree } from "../../../api/erp/basCustomerArea";
import { getDepts } from "../../../api/system/dept";
import interval from '@/components/interval/interval'
import headConfig, { reportCustomerReceiveAnalysis, reportCustomerReceiveAnalysisDetail } from '../../../headConfig'
const date = new Date().toISOString().split("T")[0];
// crud交由presenter持有
const defaultCrud = CRUD({
  title: "客户应收报表",
  optShow: {
    add: false,
    edit: false,
    del: false,
    download: true,
    leadingIn: false,
    enable: false,
    disable: false,
    pass: false,
    reject: false,
    invalid: false,
    recover: false,
    downloadDetail: false,
    print: false,
    printDetail: false,
  },
  query: {
    startDate: date,
    endDate: date,
    groupColumns:'customerId'
  },
  queryType:'post',
  queryOnPresenterCreated:false,
  url: "api/reportCustomerReceiveAnalysis/list",
  sort: "",
  crudMethod: { ...crudReportCustomerReceive },
});
const defaultForm = {
  id: null,
  salesReceiveAmount: null,
  plasticBoxAmount: null,
  returnBoxAmount: null,
  receiptAmount: null,
  actualReceiveAmount: null,
  customerId: null,
  customerName: null,
  customerCode: null,
  fCustomerId: null,
  fCustomerName: null,
  fCustomerCode: null,
};
export default {
  name: "reportCustomerReceiveAnalysis",
  components: {
    JDialog,
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    Treeselect,
    jTableColumnConfig,
    interval,
  },
  mixins: [
    presenter(defaultCrud),
    header(),
    form(defaultForm),
    crud(),
    manyTableMixin
  ],
  dicts: ["common_yes_or_no"],
  data() {
    return {
      permission: {
        add: ["admin", "reportCustomerReceive:add"],
        edit: ["admin", "reportCustomerReceive:edit"],
        del: ["admin", "reportCustomerReceive:del"],
        import: ["admin", "reportCustomerReceive:import"],
        export: ["admin", "reportCustomerReceive:export"],
        copy: ["admin", "reportCustomerReceive:copy"],
        upload: ["admin", "reportCustomerReceive:upload"],
        download: ["admin", "reportCustomerReceive:download"],
      },
      currentHeader:[],
      customerAreaIds:[],
      showInterval:false,
      rules: {},
      deptList:[],
      customerAreaList: [],
      customerTypeList: [],
      customerTypeIds: [],
      intervalList:[],
      dept: [],
      endDate:'',
      startDate:'',
      groupColumnSelectList: ['customerId'],
      groupColumn: ["customerId"],
      groupColumnList: [
        // {
        //   label: "所属二批",
        //   value: "sCustomerId",
        // },
        {
          label: "销售区域",
          value: "customerAreaId",
        },
        {
          label: "客户分类",
          value: "customerTypeId",
        },
        {
          label: "客户",
          value: "customerId",
        },
        {
          label: "业务员",
          value: "userId",
        },
      ],
      interval:[

      ],
      head:[],
    };
  },
  created() {
    getCustomerAreaTree().then((res) => {
      this.customerAreaList = res.data;
    });
    getDepts({ status: 1 }).then((res) => {
      this.deptList = res;
    });
    getCustomerTypeTree({size:999}).then(res=>{
      this.customerTypeList = res
    })
    const intervalList = localStorage.getItem(this.$options.name+'Interval')
    this.intervalList = intervalList?JSON.parse(intervalList):[] ;
    this.query.intervalList = this.intervalList
    this.head = headConfig.reportCustomerReceiveAnalysis
    this.head.unshift(  { 'dictionary': '', 'label': '客户编码', 'prop': 'customerCode', 'showName': '客户编码', 'sortable': false, 'type': '1', 'visible': true, 'width': 100 },
      { 'dictionary': '', 'label': '客户名称', 'prop': 'customerName', 'showName': '客户名称', 'sortable': false, 'type': '1', 'visible': true, 'width': 100 },)
  },
  mounted() {
    // this.crud.props.searchToggle = false
  },
  watch: {},
  methods: {
    visible(item){
      if (item.prop==="customerCode"||item.prop==="customerName") {
        return this.groupColumn.includes('customerId')
      }else if (item.prop==="userName") {
        return this.groupColumn.includes('userId')
      }else if (item.prop==="customerTypeName") {
        return this.groupColumn.includes('customerTypeId')
      }else if (item.prop==="customerAreaName") {
        return this.groupColumn.includes('customerAreaId')
      }else if (item.prop==="sCustomerName") {
        return  this.groupColumn.includes('sCustomerId')
      }else{
        return item.visible
      }
      // console.log(item,'00')
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.afterRefresh]() {
      return true;
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {},
    sumRow({ columns, data }){
      const sums = []
      for (let i in  columns) {
        if (['actualAmount', 'balanceAmount', 'beginAmount', 'curAmount','normalAmount','overDateAmount','receiveAmount','curReturnBottleBoxAmount','finalBillReceiveAmount','salesBeginFinalBillReceiveAmount'].includes(columns[i].property)) {
          let selectSum = 0
          this.$refs.table.selection.forEach(item => {
            selectSum += item[columns[i].property]
          })
          sums[i] = <p>{selectSum}
            <hr/>
            {this.crud.summary[columns[i].property] || 0}</p>
        }
        sums[0] = <p>选中
          <hr/>
          合计</p>
      }
      return sums
    },
    upInterval(e){
      this.intervalList = e
      localStorage.setItem(this.$options.name+'Interval',JSON.stringify(e))
      this.showInterval = false
      this.crud.query.intervalList = e
      this.crud.refresh()
    },
    getChange(val) {
      this.groupColumnSelectList = val;
      let groupColumn = this.groupColumnSelectList.join(",");
      this.$set(this.query, "groupColumns", groupColumn);
    },
    getNoStr(val, type, prop) {
      let str = "";
      val.forEach((item) => {
        const itemNode = this.getTreeName(this[type], item);
        str = this.getNode(itemNode, str);
      });
      this.query[prop] = str;
    },
    getTreeName(treeList, id) {
      let _this = this;
      for (let i = 0; i < treeList.length; i++) {
        let treeItem = treeList[i];
        if (treeItem.id === id) {
          return treeItem;
        } else {
          if (treeItem.children && treeItem.children.length > 0) {
            let res = _this.getTreeName(treeItem.children, id);
            if (res) {
              return res;
            }
          }
        }
      }
    },
    toQuery() {
      this.endDate=this.query.endDate
      this.startDate=this.query.startDate
      this.crud.props.searchToggle = false;
      this.crud.toQuery();
    },
    resetQuery(){
      this.customerTypeIds = []
      this.customerAreaIds = []
      this.crud.resetQuery()
    },
    toDetail(row) {
      this.query.startDate=this.startDate
      this.query.endDate=this.endDate
      const data = {
        ...this.query,
        customerId:row.customerId,
        sCustomerId:row.sCustomerId,
        customerAreaId:row.customerAreaId,
        customerTypeId:row.customerTypeId,
        userId:row.userId,
      };
      sessionStorage.setItem(
        "reportCustomerReceiveAnalysisDetail",
        JSON.stringify(data)
      );
      this.$router.push({
        path: "/report/financeReport/reportCustomerReceiveAnalysisDetail",
        query:{type:1}
      });
    },
    getNode(node, str) {
      if (node.children) {
        for (let i = 0; i < node.children.length; i++) {
          str = this.getNode(node.children[i], str);
        }
      }
      return (str += node.id + ",");
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
  },
};
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
</style>
